<template>
    <view :class="['tab tab-top', { around: around }, customClass]">
        <slot />
        <view v-for="(item, index) in list" :key="index" class="tab-item" :class="{ active: item.value === status }" @click="changeTab(item, index)">
            <view class="tab-item__text">{{ item.name }}</view>
        </view>
        <view class="tab-line" :style="{ width: `${lineW}px`, heigth: `${lineH}px`, transform: `translateX(${moveX}px)` }"></view>
    </view>
</template>
<script>
export default {
    data() {
        return {
            moveX: 0,
            rectW: []
        }
    },
    props: {
        list: Array,
        status: {
            type: [String, Number],
            default: ""
        },
        around: {
            type: Boolean,
            default: false
        },
        customClass: {
            type: String,
            default: ""
        },
        lineW: {
            type: Number,
            default: 25
        },
        lineH: {
            type: Number,
            default: 2
        },
        top: String
    },
    mounted() {
        //#ifdef H5
        window.addEventListener("resize", this.getInitData)
        //#endif
        this.getInitData()
    },
    methods: {
        getInitData() {
            this.$nextTick(() => {
                uni.createSelectorQuery()
                    .in(this)
                    .selectAll(".tab-item")
                    .boundingClientRect(rect => {
                        this.rectW = rect.map(item => ({ w: (item.width - this.lineW) / 2, l: item.left }))
                        let data = this.rectW[this.list.findIndex(val => val.value === this.status)]
                        let { w, l } = data || rectW[0]
                        this.moveX = l + w
                    })
                    .exec()
            })
        },
        changeTab(item, index) {
            let { w, l } = this.rectW[index]
            this.moveX = w + l
            this.$emit("changeTab", item, index)
        }
    },
    destroyed() {
        //#ifdef H5
        window.removeEventListener("resize", this.getInitData)
        //#endif
    }
}
</script>
